package com.yangrui.dao;

import com.yangrui.entity.Name;
import com.yangrui.util.JdbcUtil;
import java.sql.*;
import java.util.ArrayList;
import java.util.Date;


public class NameDaoImpl implements NameDao {


    @Override
    public ArrayList<Name> findAllWhere(String where) {
        Connection conn = null;
        Statement stat = null;
        ResultSet res = null;
        ArrayList<Name> list = new ArrayList<>();
        try {
            //使用封装好的jdbc代码
            conn = JdbcUtil.jdbc();

            stat = conn.createStatement();
            String sql = "select id,name,name_pinyin,create_time from inf_organization "+where;
            res = stat.executeQuery(sql);
            //放入实体类
            while (res.next()) {
                Integer id = res.getInt("id");
                String name = res.getString("name");
                String namePinyin = res.getString("name_pinyin");
                Date createTime = res.getDate("create_time");

                Name name1 = new Name(id, name, namePinyin, createTime);
                list.add(name1);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            //关闭连接
            JdbcUtil.close(conn, stat);
        }

        return list;
    }

    @Override
    public int update(Name name1) {
        Connection conn = null;
        Statement stat = null;
        int res = 0;
        try {
            conn = JdbcUtil.jdbc();
            stat = conn.createStatement();
            String sql = "update inf_organization set id='" + name1.getId() + "',name_pinyin='" + name1.getNamePinyin() + "' where id = '"+name1.getId()+"'";
            res = stat.executeUpdate(sql);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            JdbcUtil.close(conn,stat);
        }
        return res;
    }
}
